package com.zjh.securitysplit.config;

import com.zjh.securitysplit.filter.LoginFilter;
import com.zjh.securitysplit.service.MyUserDetailsService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Auther: zhaojh
 * @Date: 2025/9/4 - 09 - 04 - 0:25
 * @Description: com.zjh.securitysplit.config
 * @version: 1.0
 */
@Configuration
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private  final MyUserDetailsService myUserDetailsService ;

//    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        UserDetails user = User.builder().username("root").password("{noop}123").authorities("ROLE_USER").build();
        inMemoryUserDetailsManager.createUser(user);
        return inMemoryUserDetailsManager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.userDetailsService(userDetailsService());
        auth.userDetailsService(myUserDetailsService);
    }

    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();

    }
    @Bean
    public LoginFilter loginFilter() throws Exception {
        LoginFilter loginFilter = new LoginFilter();

        loginFilter.setFilterProcessesUrl("/doLogin");

        loginFilter.setUsernameParameter("username");
        loginFilter.setPasswordParameter("password");
//        指定认证管理器(方案一的过滤器设置authentiactionMannager)
        loginFilter.setAuthenticationManager(authenticationManagerBean());

        loginFilter.setAuthenticationSuccessHandler((request, response, authentication) -> {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("登录成功");
        });
        loginFilter.setAuthenticationFailureHandler((request, response, exception) -> {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("登录失败");
        });
        return loginFilter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
//                .mvcMatchers("/doLogin").permitAll()
                .anyRequest().authenticated()
                .and()
                //异常处理
                .exceptionHandling()
                //认证失败处理异常
                .authenticationEntryPoint((request, response, authException) -> {
                    response.setContentType("application/json;charset=utf-8");
                    response.setStatus(401);
                    response.getWriter().write("请认证");
                })
                .and()
                .formLogin()
                .and()
                .csrf().disable();
        //addFilterAt 替换为自己
        // addFilterBefore 在此过滤器之前添加特定过滤器
        // addFilterAfter 在此过滤器之后添加特定过滤器
        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);

    }
}
